package com.saycode.portal.article.controller;

import com.saycode.back.articleType.service.ContentTypeService;
import com.saycode.common.MethodUtil;
import com.saycode.common.enums.StatusEnum;
import com.saycode.common.beans.Article;
import com.saycode.common.beans.ArticleContent;
import com.saycode.portal.article.service.ArticleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * Created by zhangyanhui on 2017/6/14.
 */
@Controller("portal/article")
@RequestMapping("portal/article")
public class ArticleController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("portal/articleService")
    private ArticleService articleService;

    @Autowired
    @Qualifier("back/contentTypeService")
    private ContentTypeService contentTypeService;

    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String detail(ModelMap map, @PathVariable("id") Long id) {
        Article article = articleService.findById(id);
        ArticleContent content = articleService.findContentById(id);
        map.put("article",article);
        map.put("content",content);
        return "portal/article/detail";
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(ModelMap map, @Param("type") String type,@Param("pageNum") Integer pageNum) {
        if(pageNum == null) pageNum = 1;
        logger.info("type="+type);
        logger.info("pageNum="+pageNum);
        if(MethodUtil.isNull(type)) type = null;
        Page<Article> page = articleService.findByStatusAndContentType(StatusEnum.published,type,pageNum);
        List<Article> listArticle = page.getContent();
        map.put("contentTypeList",contentTypeService.findAll());
        map.put("hasNext",page.getTotalPages() > pageNum);
        map.put("hasPrev",pageNum > 1);
        map.put("pageNum",pageNum);
        map.put("articleList",listArticle);
        map.put("type",type);
        return "portal/article/list";
    }


}
